﻿using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.IO;

using RexToy.Configuration;
using RexToy.IoC;
using RexToy.Logging;

using MGAS.Model;
using MGAS.UI.View;

namespace MGAS.UI
{
    static class Program
    {
        private static IKernal _ctx;
        public static IKernal Context
        {
            get { return _ctx; }
        }

        private static bool _restart;
        public static bool Restart
        {
            get { return _restart; }
            set { _restart = value; }
        }

        [STAThread]
        static void Main()
        {
            AppConfig.Load(ConfigFactory.CreateXmlConfig());

            _ctx = new Kernal("main");
            var c = _ctx.Lookup<ISensorDataCollector>();
            try
            {
                c.StartCollect();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

            Application.ThreadException += new System.Threading.ThreadExceptionEventHandler(Application_ThreadException);
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            
            Application.Run(new FrmMain());
            while (_restart)
            {
                _restart = false;

                _ctx.Lookup<ISensorDataBlock>().InitializeAddressList();
                _ctx.Lookup<ISensorDataCollector>().InitializeAddressList();
                Application.Run(new FrmMain());
            }            

            try
            {
                c.StopCollect();
                _ctx.TearDown(c);
            }
            finally
            {
                _ctx.Dispose();
            }
        }

        static void Application_ThreadException(object sender, System.Threading.ThreadExceptionEventArgs e)
        {
            MessageBox.Show(e.Exception.Message);
            LogContext.GetLogger("MGAS").Error(e.Exception.ToString());
            _ctx.Dispose();
            Application.Exit();
        }
    }
}
